const TOKEN = 'tcckToken'
App({
  onLaunch(options) {
    // 第一次打开
    // options.query == {number:1}
    console.info('App onLaunch');
  },
  onShow(options) {
    // 从后台被 scheme 重新打开
    // options.query == {number:1}
  },
  globaldata: {
    // serverurl:'http://ding.cx',
    serverurl: 'https://ding.api.0573vote.com',
    authCode: '',
  },
  // 封装网络请求
  https(httpstype, url, data=null) {
    dd.showLoading();
    // 获取token
    const token = dd.getStorageSync({
      key: TOKEN,
    });
    
    let endurl = encodeURI(this.globaldata.serverurl + url);
    return new Promise((resolve, reject) => {
      dd.httpRequest({
        headers: {
          "Content-Type": 'application/json;charset=utf-8',
          Authorization: 'Bearer ' + token ? token.data : 'null'
        },
        url: endurl,
        method: httpstype,
        data: data,
        dataType: 'json',
        success: (res) => {
          // dd.confirm({
          //   title: 'success',
          //   content: JSON.stringify(res),
          //   success: (res) => {
          //   },
          //   fail: () => {},
          //   complete: () => {},
          // });
          resolve(res)
        },
        fail: (errorRes) => {

          // dd.confirm({
          //   title: 'fail',
          //   content: JSON.stringify(errorRes),
          //   success: (res) => {
          //   },
          //   fail: () => {},
          //   complete: () => {},
          // });

          if (errorRes.status === 401) {
            dd.getAuthCode({
              corpId: 'dingf3b170a7280901ae35c2f4657eb6378f',
              success: (authCodeRes) => {
                const { authCode } = authCodeRes;
                this.https('GET','/api/Auth/Login',{ authCode }).then(loginRes => {
                  console.log('sdfsdf', loginRes.data)

                  dd.setStorage({
                    key: TOKEN,
                    data: loginRes.data,
                  });

                  dd.reLaunch({
                    url: '/pages/index/index',
                    success: () => {},
                    fail: () => {},
                    complete: () => {},
                  });

                })
              },
              fail: () => {},
              complete: () => {},
            })
            
          }
          reject(errorRes)
 
        },
        complete: (res) => {
          dd.hideLoading()
        }
      })
    })
  }
});
